<template>
  <el-card class="page-container">
    <template #header>
      <div class="header">
        <div class="title">更换密码</div>
      </div>
    </template>
    <el-row>
      <el-col :span="12">
        <el-form class="form-inline" ref="pwdFormRef" :model="pwdForm" :rules="rules" label-width="120px">
          <el-form-item label="原密码" prop="oldPassword">
            <el-input v-model="pwdForm.oldPassword" type="password" show-password></el-input>
          </el-form-item>
          <el-form-item label="新密码" prop="newPassword">
            <el-input v-model="pwdForm.newPassword" type="password" show-password></el-input>
          </el-form-item>
          <el-form-item>
            <el-button @click="router.back()">取消</el-button>
            <el-button type="primary" @click="saveHandle"> 保存 </el-button>
          </el-form-item>
        </el-form>
      </el-col>
    </el-row>
  </el-card>
</template>
<script setup lang="ts">
import { putBusinessPwdAPI } from '@/api/business/business'
import { reactive, ref } from 'vue'
import { useRouter } from 'vue-router'
import { useUserStore } from '@/stores/userStore'
import { ElForm, ElMessage, FormRules } from 'element-plus'
import { pwdValidate } from '@/utils/validator'
import { putAdminPwdAPI } from '@/api/admin/admin'
const router = useRouter()
const userStore = useUserStore()
// 当前登录用户id
const id = userStore.user.id
const pwdForm = ref({ oldPassword: '', newPassword: '' })

const pwdFormRef = ref<InstanceType<typeof ElForm> | null>(null)
const rules = reactive<FormRules<typeof pwdForm>>({
  oldPassword: [{ validator: pwdValidate, trigger: 'blur' }],
  newPassword: [{ validator: pwdValidate, trigger: 'blur' }],
})
const saveHandle = async () => {
  pwdFormRef.value?.validate(async (vaild: boolean) => {
    if (vaild) {
      let params = {
        id: id,
        ...pwdForm.value,
      }
      try {
        if (userStore.rule === 'admin') {
          await putAdminPwdAPI(params)
        } else {
          await putBusinessPwdAPI(params)
        }
        ElMessage.success('更改成功')
        userStore.logout()
        router.push('/login')
      } catch (error) {
        console.log(error)
      }
    } else {
      ElMessage.error('表单校验失败')
    }
  })
}
</script>
<style scoped></style>
